<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;


require_once __DIR__ .  '/../../Connection.php';
//https://www.workerman.net/doc/gateway-worker/mysql.html
// https://www.workerman.net/doc/workerman/components/workerman-mysql.html
/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
     /**
     * 新建一个类的静态成员，用来保存数据库实例
     */
    public static $db = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {  
        $SQL_host = "127.0.0.1"; //数据库主机:端口
        $SQL_user = "www_im_com"; //数据库用户名
        $SQL_pass = "RXzaSWyerphchaaA"; //数据库密码
        $SQL_name = "www_im_com"; //数据库表名
        self::$db = new \Workerman\MySQL\Connection($SQL_host, '3306', $SQL_user, $SQL_pass, $SQL_name);
    }
    
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        Gateway::sendToClient($client_id, json_encode(array(
            'type'      => 'init',
            'client_id' => $client_id
        )));
        
        // 向所有人发送
        Gateway::sendToAll("$client_id login...");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
       //获取某分组当前在线成连接数（多少client_id在线）
       $RoomCount = Gateway::getClientIdCountByGroup("room_id_web_msg");
       //获取当前在线连接总数（多少client_id在线）。
       $AllCCount = Gateway::getAllClientIdCount();
       //获取全局所有在线uid数量。
       $AllUCount = Gateway::getAllUidCount();
       // 发来的消息$commend
        $message = trim($message);
        // 向所有人发送 
        Gateway::sendToAll("web在线数: $RoomCount ,手机在线数: $AllUCount ,All在线数: $AllCCount ,said= $client_id \r\n $message");
        //web在线检测
        if($message == "1"){
            Gateway::sendToClient($client_id, "2");
            return ;
        }
        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            return ;
        }
        //["sub",["user-89146","global"]]
        if (strpos($message, '["sub",[') !== false) {  
            Gateway::sendToClient($client_id, json_encode(array('ok',$message,"欢迎进入WEB...")));
            Gateway::joinGroup($client_id, "room_id_web_msg");
            return ;
        } 
        $message_type = $message_data['type'];
        //添加卡片类型
        if($message_data['type'] == "MsgCard"){
            $message_data['type'] = "MsgText";
        }
         // 根据类型执行不同的业务
        switch($message_data['type'])
        {
            // 客户端回应服务端的心跳
            case 'ping':
                return;
            case 'jd_juan':
                $skuName = $message_data["skuName"];
                $skuId = $message_data["skuId"];
                $promotionUrl = $message_data["promotionUrl"];
                
                // id skuId url skuName time
                $msgtime = time();
                // 使用数据库实例
                // $ret = self::$db->select('*')->from('im')->where('id > 1')->query();
                // Gateway::sendToClient($client_id, var_export($ret, true));
                
                $ret = self::$db->query("INSERT INTO `jd_juan` ( skuId,url,skuName,time ) VALUES ( '$skuId','$promotionUrl','$skuName',$msgtime )");
                
                return;
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'bind':
                
                $client_idxx = $message_data["client_id"];
                $uid = $message_data["uid"];
                $uniqueName = $message_data["uniqueName"];
                
                Gateway::bindUid($client_id, $uid);
                
                Gateway::sendToAll(json_encode(array(
                    'type'      => 'toast',
                    'content' => "$uniqueName ID: $uid 上线了～")));
                return;
            case 'MsgText':
                $sid = $message_data["sid"];
                $content = $message_data["content"];
                $itemId = $message_data["itemId"];
                $mainPic = $message_data["mainPic"];
                $owner_userId = $message_data["owner_userId"];
                $owner_fishNick = $message_data["owner_fishNick"];
                $to_userId = $message_data["to_userId"];
                $to_fishNick = $message_data["to_fishNick"];
                
                $owner_logo = $message_data["owner_logo"];
                $to_logo = $message_data["to_logo"];
                $msgtime = time();
                // 使用数据库实例
                // $ret = self::$db->select('*')->from('im')->where('id > 1')->query();
                // Gateway::sendToClient($client_id, var_export($ret, true));
                
                $ret = self::$db->query("INSERT INTO `im` ( sid,content,itemId,mainPic,owner_userId,owner_fishNick,to_userId,to_fishNick,owner_logo,to_logo,msgtime ) VALUES ( '$sid','$content','$itemId','$mainPic','$owner_userId','$owner_fishNick','$to_userId','$to_fishNick','$owner_logo','$to_logo',$msgtime )");

                //Gateway::sendToAll(  var_export($ret, true));
                //$db->info("im", "sid,content,itemId,mainPic,owner_userId,owner_fishNick,to_userId,to_fishNick", "'$sid','$content','$itemId','$mainPic','$owner_userId','$owner_fishNick','$to_userId','$to_fishNick'");

                //$db->info("im", "sid,content,itemId,mainPic,owner_userId,owner_fishNick,to_userId,to_fishNick", "'$sid','$content','$itemId','$mainPic','$owner_userId','$owner_fishNick','$to_userId','$to_fishNick'");
                
                //["message",{"from":"89146","from_name":"vipbtt","from_avatar":"/static/avatar.jpg","to":"88744","to_name":"wangxd","to_avatar":"/static/avatar.jpg","content":"123456789\n","timestamp":1709157595,"type":"friend","sub_type":"message","mid":"17500097","uniqueId":"1709157595365"},"user-88744"]
                
                $items["from"]=$sid;
                $items["from_name"]=$to_fishNick;
                $items["from_avatar"]=$mainPic;
                //$items["from_avatar"]=$to_logo;//new 进入聊天看到时头像，不好
                $items["to"]=$owner_userId;
                $items["to_name"]=$owner_fishNick;
                $items["to_avatar"]=$owner_logo;
                $items["content"]=$content;
                $items["timestamp"]=time();
                $items["type"]="friend";
                $items["mid"]=time();
                $items["uniqueId"]="17".time();
                $items["sub_type"]="message";
                
                $items["from_name"]="[".$owner_fishNick."]".$to_fishNick.']';//new
        
                if($message_type == "MsgCard"){
                    if($to_userId == "100"){
                        $items["sub_type"]="notice";
                    }
                }
                //替换视频制表符
                if (strpos($content, '4   ') !== false) {  
                    //file[IMG_0128_compressMedium.mp4	5.43 MB](http://wantu-xm4-xianyu-video-hz.oss-cn-hangzhou.aliyuncs.com/aus/xianyu_imvod_private/187843300/643DC472AB8643A8962328B6A5D80E7F?video_id=451430442800)
                    $originalText = $content; 
                    $searchString = "4   "; //[IMG_0128_compressMedium.mp4
                    $replaceString =  '4	';  
                    $items["content"] = str_replace($searchString, $replaceString, $originalText); 
                }
        
                $new_message = json_encode(array('message',$items,"user-89146"));
                
                // $new_message = '["message",{"from":"88744","from_name":"vipbtt","from_avatar":"/static/avatar.jpg","to":"89146","to_name":"wangxd","to_avatar":"/static/avatar.jpg","content":"123456789\n","timestamp":1709155595,"type":"friend","sub_type":"message","mid":"17500098","uniqueId":"1709157595345"},"user-89146"]';
                
                if(! $RoomCount){
                    
                    return;
                }
                Gateway::sendToGroup("room_id_web_msg" ,$new_message);
                return;
        }
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       GateWay::sendToAll("$client_id logout\r\n");
   }
}
